﻿using System.Reflection.Metadata;

namespace Study005_Async_Task;

/// <summary>
///  封装一个异步方法，下载给定的网址，如果下载是吧，等待500ms再尝试，尝试3次任然失败，抛出异常“下载失败”。
/// </summary>
public class HomeWork
{
    /// <summary>
    /// 获取网页内容
    /// </summary>
    /// <param name="url">网页地址</param>
    /// <returns>网页内容</returns>
    /// <exception cref="Exception">尝试3次失败后，抛出"下载失败"</exception>
    public static async Task<string> GetWebStringAsync(string url)
    {
        int index = 1;
        while (index < 4)
        {
            Console.WriteLine("第" + index++ + "次尝试");
            using HttpClient httpClient = new();
            try
            {
                return await httpClient.GetStringAsync(url);
            }
            catch (Exception)
            {
                await Task.Delay(500);
            }
        }
        throw new Exception("下载异常");

    }

}
